<template>
  <div style="margin-top: 10px" class="preOrder">
    <div style="background-color: white; padding: 10px">
      <!-- 状态 -->
      <el-steps :active=1 align-center finish-status="success" process-status="wait">
        <el-step title="确认商品"></el-step>
        <el-step title="提交订单"></el-step>
        <el-step title="支付订单"></el-step>
      </el-steps>
      <!--收货地址-->
      <el-card shadow="never" :border="false" style="padding: 10px; margin-bottom: 10px; border-bottom: 1px solid #eee">
        <el-row style="border-bottom: 2px solid red;">
          <h2 style="color: red;">收货地址</h2>
        </el-row>
        <el-row v-for="item in addressData" :key="item.id" class="address-box" style="display: flex;">
          <el-col :span="4">
            <el-radio v-model="chooseAddress" :label="item"><span class="address-label">联系人：</span>{{ item.linkUser
              }}</el-radio>
          </el-col>
          <el-col :span="4"><span style="margin-left: 20px"><span class="address-label">联系电话：</span>{{ item.linkPhone
              }}</span></el-col>
          <el-col :span="14"><span style="margin-left: 20px"><span class="address-label">送货地址：</span>{{ item.linkAddress
              }}</span></el-col>

<!--          <el-col :span="2">操作</el-col>-->
        </el-row>
        <div class="add-box" style="display: flex; justify-content: flex-end;">
          <el-button icon="el-icon-plus" type="primary" plain size="small"
            @click="() => { this.showAddAddressDialog = !this.showAddAddressDialog }"></el-button>
        </div>
      </el-card>
      <!--        商品确认-->
      <el-row style="border-bottom: 2px solid red;">
        <h2 style="color: red;">商品确认</h2>
      </el-row>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="商品图片" width="150">
          <template slot-scope="scope">
            <el-image :src="scope.row.skuUrl" style="width: 100px; height: 100px;" fit="contain"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="商品名称">
          <template slot-scope="scope">
            <el-link type="success" @click="redirectToSpu(scope.row.spuId)">{{
              scope.row.spuName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="skuAttribute" label="商品属性">
          <template slot-scope="{row}">
            <span ><el-tag  type="danger">{{ JSON.parse(row.skuAttribute)?.color }}
              </el-tag></span>
            <span style="margin-left: 10px"><el-tag  type="danger">{{ JSON.parse(row.skuAttribute)?.size
                }}</el-tag></span>
          </template>
        </el-table-column>
        <el-table-column label="单价" prop="salePrice"></el-table-column>
        <el-table-column label="数量" prop="count"></el-table-column>
        <el-table-column label="小计">
          <template slot-scope="scope">
            <p style="color: green">{{ scope.row.salePrice * scope.row.count }}</p>
          </template>
        </el-table-column>
      </el-table>

      <!-- 提交订单 -->
      <div style="margin-top: 10px">
        <div style="background-color: white; padding: 10px">
          <div style="color: red; text-align: right">
            <div>
              <span>总金额：</span>
              <span>￥ {{ totalPrice }}</span>
            </div>
            <!-- <div style="text-align: right; color: #999; font-size: 12px; padding: 5px 0">
              运费： ￥ 0
            </div>
            <div style="text-align: right; color: #999; font-size: 12px;">
              优惠： - ￥{{ discount }}
            </div> -->
            <div style="padding: 10px 0">
              <el-button style="background-color: red; color: white; width: 100px" @click="submitOrder">提交订单</el-button>
            </div>
          </div>
        </div>
      </div>
      <!--地址添加-->
      <el-dialog title="添加地址" :visible.sync="showAddAddressDialog" width="50%" center >
        <el-card shadow="never">
          <el-form ref="addressForm" :model="address" :rules="rules" label-width="auto" size="small"
            style="width: 400px; margin: 0 auto;">
            <el-form-item label="收货人" prop="linkUser">
              <el-input style="min-width: 300px;" v-model="address.linkUser"></el-input>
            </el-form-item>
            <el-form-item style="min-width: 300px;" label="收货人电话" prop="linkPhone">
              <el-input v-model="address.linkPhone"></el-input>
            </el-form-item>
            <el-form-item label="选择地址">
              <el-cascader style="min-width: 300px;" size="large" v-model="prefixAddress"
                :options="options"></el-cascader>
            </el-form-item>
            <el-form-item label="详细地址" prop="linkAddress">
              <el-input style="min-width: 300px;" v-model="address.linkAddress"></el-input>
            </el-form-item>
            <div class="submit-box" style="display: flex;justify-content: center;align-content: center;">
              <el-button type="success" @click="addAddress('addressForm')">立即添加地址</el-button>
            </div>
          </el-form>
        </el-card>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import { submitSOrderBatch } from "@/api/sOrder";
import { getAllAddress, saveAddress, findDistrict } from "@/api/address";
import { deleteCartBatch } from '@/api/sCart'
import { prePay } from '@/api/pay'
import { getUser } from "@/utils/storage";
import {getSpuById} from "@/api/goods";
import { mapState, mapActions, mapMutations } from "vuex"
export default {
  name: "cart",
  data() {
    return {
      address: {
        linkUser: '',
        linkAddress: '',
        linkPhone: '',
        userId: ''
      },
      chooseAddress: null,
      user: {},
      tableData: [],
      addressData: [],
      carts: [],
      discount: 0,
      orders: [],
      showAddAddressDialog: false,
      rules: {
        linkUser: [
          { required: true, message: '输入联系人', trigger: 'blur' }
        ],
        linkPhone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        linkAddress: [
          { required: true, message: '请输入收货地址', trigger: 'blur' }
        ],
      },
      options: [],
      prefixAddress: '',
      addressList: [],

    }
  },
  computed: {
    ...mapState('sCart', ['sCartList', 'selectedList']),
    totalPrice() {
      return this.selectedList.reduce((sum, item) => sum + (item.salePrice * item.count), 0)
    }
  },
  watch: {
    selectedList: {
      handler(newVal) {
        // console.log(newVal)
        this.tableData = this.selectedList
        if (newVal?.length === 0 || newVal == undefined) {
          this.$message.error('页面过期！')
          this.$router.push({
            path: '/front/cart'
          })
        }
      },
      immediate: true, // 在绑定时立即以当前的 selectedList 值触发回调
      deep: true // 深度监听，用于对象或数组
    }
  },
  async created() {
    this.user = getUser()
    if (!this.user) {
      this.$message({
        type: "warning",
        message: '请登录！'
      })
      return
    }
    await this.loadAddress()
    await this.loadDistrict()
  },
  methods: {
    redirectToSpu(spuId) {
      getSpuById(spuId).then(res => {
        if (res.code === '0'){
          this.$store.commit('spu/setSelectedSpu',res.data)
          this.$router.push("/front/goods")
        }
      })
    },
    async submitOrder() {
      if (!this.chooseAddress) {
        this.$message({
          type: 'warning',
          message: '请选择收货地址！'
        })
        return
      }
      // 合成订单
      // console.log(this.selectedList)
      this.orders = this.selectedList.map(item => {
        return {
          spuId: item.spuId,
          spuName: item.spuName,
          skuId: item.skuId,
          detail: item.skuAttribute,
          count: item.count,
          price: item.price,
          salePrice: item.salePrice,
          totalPrice: item.price * item.count,
          payPrice: item.salePrice * item.count,
          userId: this.user.id,
          linkUser: this.chooseAddress.linkUser,
          linkPhone: this.chooseAddress.linkPhone,
          linkAddress: this.chooseAddress.linkAddress,
          state: 0,
        }
      })
      console.log(this.orders)
      // 提交订单
      const { data: orders } = await submitSOrderBatch(this.orders)
      // 删除购物车
      let ids = this.selectedList.map(item => item.id)
      await deleteCartBatch({ userId: this.user.id, ids: ids })

      this.$message.success('提交订单成功')
      // 准备支付
      const { data: aliPay } = await prePay(orders)
      // 跳转支付
      this.$router.push({
        name: 'Pay',
        params: {
          aliPay: aliPay
        }
      })
      // console.log(res)
      // window.open(`http://127.0.0.1:9999/alipay/pay?subject=${aliPay.subject}&traceNo=${aliPay.traceNo}&totalAmount=${aliPay.totalAmount}`,'_self')

    },
    async loadAddress() {
      // 获取收货地址
      await getAllAddress().then(res => {
        this.addressData = res.data
        this.chooseAddress = this.addressData[0]
      })
      // console.log(this.options)
    },
    //在打开表单时再加载可选地址，提高页面响应速度
    async loadDistrict() {
      // 获取可选地址
      const { data } = await findDistrict()
      this.addressList = data
      if (data && data.length) {
        this.options = this.buildTree(this.addressList)
        // console.log(this.options)
      }
    },
    async addAddress(addressForm) {
      //数组转字符串
      this.prefixAddress = this.prefixAddress.join(',').replace(/,/g, '')
      this.address.linkAddress = this.prefixAddress + this.address.linkAddress
      // console.log(this.address)
      this.address.userId = this.user.id
      await this.$refs[addressForm].validate(async(valid) => {
        if (valid) {
          await saveAddress(this.address)
          this.address = {}
          this.$message.success('添加地址成功！')
          this.showAddAddressDialog = !this.showAddAddressDialog
          await this.loadAddress()
        } else {
          this.$message.warning('请输入正确地址信息！')
          return false;
        }
      });
    },

    buildTree(data) {
      const tree = [];
      const map = {};

      data.forEach(item => {
        map[item.id] = { ...item, label: item.name, value: item.name, children: [] };
      });

      data.forEach(item => {
        const parent = map[item.pid];
        if (parent) {
          parent.children.push(map[item.id]);
        } else {
          tree.push(map[item.id]);
        }
      });
      // 移除没有子节点的 `children` 属性
      function removeEmptyChildren(node) {
        if (node.children && node.children.length === 0) {
          delete node.children;
        } else if (node.children) {
          node.children.forEach(removeEmptyChildren);
        }
      }

      tree.forEach(removeEmptyChildren);
      return tree;
    }
  }
}
</script>

<style scoped>
/* 图片
https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/7b6b02396368c9314528c0bbd85a2e06.png
https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/c66f98cff8649bd5ba722c2e8067c6ca.jpg
*/
.address-box {
  padding: 10px 0;
  color: #555;
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.address-box::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.address-box::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 4px;
}

.address-box::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}

.address-label {
  font-size: 12px;
  color: #cca2a2;
}
</style>
